package main

import (
	"fmt"
	"strconv"
)

/*
	完成单链表的增删改查，节点为梁山好汉
 */
type Node struct {
	no int
	name string
	nickName string
	next *Node
}

func (n *Node) String() string {
	return "好汉编号:"+strconv.Itoa(n.no)+",好汉名字:"+n.name+",好汉称号:"+n.nickName
}

/*
	单链表结构体，包含一个头结点，但是头结点里不存放值
 */
type SingleLinkedList struct {
	head Node
}

/*
	向链表的末尾插入节点
 */
func (sl *SingleLinkedList) insertToRearList (node *Node) {
	temp := &sl.head
	for temp.next!=nil {
		temp = temp.next
	}
	temp.next = node
}

/*
	根据英雄的编号从小到大插入节点
 */
func (sl *SingleLinkedList) insertToList (node *Node) {
	if sl.head.next == nil {
		sl.head.next = node
	}else{
		temp := &sl.head
		for temp.next!=nil && temp.next.no<node.no{
			temp = temp.next
		}
		//有两种情况，1、temp为尾节点，2、temp不为尾节点
		node.next = temp.next
		temp.next = node
	}
}

/*
	根据英雄的编号删除节点
*/
func (sl *SingleLinkedList) deleteFromList (no int) {
	if sl.head.next == nil {
		fmt.Println("链表为空")
	}else{
		temp := &sl.head
		for temp.next!=nil && temp.next.no != no{
			temp = temp.next
		}
		//有两种情况，1、temp为尾节点，2、temp不为尾节点
		if temp.next == nil {
			//此时表示未找到该节点
			fmt.Println("未找到该节点")
		}else {
			temp.next = temp.next.next
		}
	}
}

/*
	将链表的所有节点打印输出
 */
func (sl *SingleLinkedList) showList () {
	if sl.head.next == nil {
		fmt.Println("链表为空")
		return
	}
	temp := &sl.head
	for temp.next!=nil {
		temp = temp.next
		fmt.Println(temp)
	}
}


func main() {
	headNode := Node{}
	sl := SingleLinkedList{
		head: headNode,
	}

	n1 := Node{
		no:       1,
		name:     "晁盖",
		nickName: "托塔天王",
		next:     nil,
	}

	n2 := Node{
		no:       2,
		name:     "吴用",
		nickName: "智多星",
		next:     nil,
	}

	n3 := Node{
		no:       3,
		name:     "林冲",
		nickName: "豹子头",
		next:     nil,
	}

	n4 := Node{
		no:       4,
		name:     "武松",
		nickName: "行者",
		next:     nil,
	}

	sl.insertToList(&n3)
	sl.insertToList(&n1)
	sl.insertToList(&n2)
	sl.insertToList(&n4)

	sl.showList()

	sl.deleteFromList(1)
	sl.showList()
	sl.deleteFromList(4)
	sl.showList()
	sl.deleteFromList(2)
	sl.showList()
}
